const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

var StringUtils = {
  randomLine: function(length) {
    let line = '';
    for (let i = 0; i < length - 1; i++) {
      line += String.fromCharCode(Math.floor(Math.random() * 26) + 97);
    }
    return line + '\n';
  },
  
  randomLines: function(totalSizeKB, linesCount) {
    let lines = "";
    let totalSize = 0;
    let lineLength = Math.floor(totalSizeKB * 1024 / linesCount);
    for (let i = 0; i < linesCount - 1; i++) {
      let line = this.randomLine(lineLength);
      lines += line;
      totalSize += line.length;
    }

    lines += this.randomLine(totalSizeKB * 1024 - totalSize);
    return lines;
  }
};

var FileUtils = {
  exists: function(filename, skipLastName=false) {
    if (skipLastName) {
      filename = path.dirname(filename)
    }
    return fs.existsSync(filename);
  },

  createDir: function(dirname, skipLastName=false) {
    if (skipLastName) {
      dirname = path.dirname(dirname)
    }
    
    if (!fs.existsSync(dirname)) {
      fs.mkdirSync(dirname, { recursive: true })
      console.log('Created directory ' + dirname);
    }
  },
  
  saveFile: function(filePath, fileContent) {
    this.createDir(filePath, true);
    fs.writeFileSync(filePath, fileContent);
    console.log('save file: ' + filePath);
  },
  
  getHashFileNameByIndex: function(index, depth = 2) {
    const md5 = crypto.createHash('md5').update(index.toString()).digest('hex')
    let dirs = []
    
    for (let i = 0; i < depth; i++) {
      dirs.push(md5.slice(i * 2, i * 2 + 2))
    }
    
    const filename = `${index}_${md5}.txt`
    return path.join(...dirs, filename);
  },
}

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  // CommonJS 模块导出
  module.exports = {
    FileUtils,
    StringUtils,
  };
} else if (typeof define === 'function' && define.amd) {
  // ES6 模块导出
  define([], FileUtils, StringUtils);
} else if (typeof exports === 'object') {
  // Node/CommonJS
  module.exports = {
    FileUtils,
    StringUtils,
  };
} else {
  // Exported as a string, for Closure Compiler in advanced mode.
  var globalVar = (function() { return this; })();
  globalVar.FileUtils = FileUtils;
  globalVar.StringUtils = StringUtils;
}
